package game.breeze.message.codec.mina;

import game.breeze.message.AppMessage;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

public class MinaMessageDecoder implements MessageDecoder {

	@Override
	public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
		if (in.remaining() < 8) {
			return MessageDecoderResult.NEED_DATA;
		}

		int p = in.position();
		int type = in.getInt();
		int length = in.getInt();

		in.position(p);

		if (in.remaining() < length) {
			return MessageDecoderResult.NEED_DATA;
		}

		return MessageDecoderResult.OK;
	}

	@Override
	public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		try {
			int type = in.getInt();
			int length = in.getInt();
			AppMessage message = AppMessage.createMessage(type, length);
			byte[] data = new byte[length];
			in.get(data);
			message.getBuffer().writeBytes(data);
			out.write(message);
			return MessageDecoderResult.OK;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return MessageDecoderResult.NOT_OK;
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception {

	}
}
